const fs = require('fs');
const csv = require('csv-parser');
const mysql = require('mysql');
const crypto = require('crypto');

// 创建MySQL数据库连接
const pool = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345678',
    database: 'tpadmin'
});

// 从 CSV 文件中读取数据并插入到数据库中
fs.createReadStream('users.csv')
    .pipe(csv())
    .on('data', (row) => {
        const { username, password, points } = row;

        // Check if the username already exists in the database
        pool.query(
            'SELECT * FROM tpadmin_user_user WHERE username = ?',
            [username],
            (error, results, fields) => {
                if (error) {
                    console.error(`查询用户名 ${username} 失败：`, error);
                } else {
                    if (results.length > 0) {
                        console.log(`用户名 ${username} 已存在`);
                    } else {
                        const salt = crypto.randomBytes(16).toString('hex');
                        const hashedPassword = crypto
                            .createHash('md5')
                            .update(password + salt)
                            .digest('hex');

                        pool.query(
                            'INSERT INTO tpadmin_user_user (username, password, salt, email, points) VALUES (?, ?, ?, ?, ?)',
                            [username, hashedPassword, salt, '', points],
                            (error, results, fields) => {
                                if (error) {
                                    console.error(`插入用户 ${username} 失败：`, error);
                                } else {
                                    console.log(`插入用户 ${username} 成功`);
                                }
                            }
                        );
                    }
                }
            }
        );
    })
    .on('end', () => {
        console.log('所有用户已插入到数据库中');
    });

